package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.SServiceOrderTrailTypeEnum;
import cn.huiyunche.base.service.interfaces.CWaybillTrailService;
import cn.huiyunche.base.service.interfaces.GDMapService;
import cn.huiyunche.base.service.interfaces.SServiceOrderTrailService;
import cn.huiyunche.base.service.mappers.BAreaMapper;
import cn.huiyunche.base.service.mappers.CWaybillDetailMapper;
import cn.huiyunche.base.service.mappers.CWaybillTrailMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 运单物流信息接口实现类
 *
 * @author Administrator
 */
@Service
public class CWaybillTrailServiceImpl implements CWaybillTrailService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CWaybillTrailServiceImpl.class);

    @Autowired
    private CWaybillTrailMapper cWaybillTrailMapper = null;

    @Autowired
    private BAreaMapper bAreaMapper = null;

    @Autowired
    private GDMapService gdMapService = null;

    @Autowired
    private SServiceOrderTrailService sServiceOrderTrailService = null;

    @Autowired
    private CWaybillDetailMapper cWaybillDetailMapper = null;

    private CWaybillDetailMapper getCWaybillDetailMapper() {
        return this.cWaybillDetailMapper;
    }

    private SServiceOrderTrailService getSServiceOrderTrailService() {
        return this.sServiceOrderTrailService;
    }

    private GDMapService getGDMapService() {
        return gdMapService;
    }

    private CWaybillTrailMapper getCWaybillTrailMapper() {
        return this.cWaybillTrailMapper;
    }

    private BAreaMapper getBAreaMapper() {
        return this.bAreaMapper;
    }

    @Override
    public List<CWaybillTrail> selectByExample(CWaybillTrailExample example) {
        LOGGER.info("select cwaybill trail by example params example : {}.", example);
        try {
            return this.getCWaybillTrailMapper().selectByExample(example);
        } catch (Exception e) {
            LOGGER.error("select cwaybill trail by example : {}.", e);
            throw new BusinessException("查询运单物流信息异常");
        }
    }

    @Override
    public Long add(CWaybillTrail cWaybillTrail) throws Exception {
        LOGGER.info("add params : {}", cWaybillTrail);
        if (cWaybillTrail.getWaybillId() == null) {
            LOGGER.info("waybillId is not null");
            throw new BusinessException("运单ID不能为空");
        }
        if (StringUtils.isBlank(cWaybillTrail.getProvinceCode())) {
            LOGGER.info("provinceCode is not null");
            throw new BusinessException("省编码不能为空");
        } else if (StringUtils.isBlank(cWaybillTrail.getCityCode())) {
            LOGGER.info("cityCode is not null");
            throw new BusinessException("市编码不能为空");
        } else if (StringUtils.isBlank(cWaybillTrail.getCountyCode())) {
            LOGGER.info("countyCode is not null");
            throw new BusinessException("区县编码不能为空");
        }
        // 判断上报日期
        CWaybillTrailExample example = new CWaybillTrailExample();
        example.setOrderByClause("id desc");
        example.createCriteria().andWaybillIdEqualTo(cWaybillTrail.getWaybillId());
        List<CWaybillTrail> list = this.getCWaybillTrailMapper().selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {
            CWaybillTrail cTrail = list.get(0);
            if (cWaybillTrail.getUpdateTime() == null) {
                cWaybillTrail.setUpdateTime(new Date());
            }
            if (cWaybillTrail.getUpdateTime().before(cTrail.getUpdateTime())) {
                LOGGER.info("The current report date cannot be less than the last reported to date");
                throw new BusinessException("当前上报日期不能小于最后上报日期");
            }
        }
        if (StringUtils.isNotBlank(cWaybillTrail.getProvinceCode())) {
            BAreaExample example1 = new BAreaExample();
            example1.createCriteria().andCodeEqualTo(cWaybillTrail.getProvinceCode());
            List<BArea> bAreas = this.getBAreaMapper().selectByExample(example1);
            if (CollectionUtils.isNotEmpty(bAreas)) {
                cWaybillTrail.setProvinceName(bAreas.get(0).getName());
            }
        }
        if (StringUtils.isNotBlank(cWaybillTrail.getCityCode())) {
            BAreaExample example1 = new BAreaExample();
            example1.createCriteria().andCodeEqualTo(cWaybillTrail.getCityCode());
            List<BArea> bAreas = this.getBAreaMapper().selectByExample(example1);
            if (CollectionUtils.isNotEmpty(bAreas)) {
                cWaybillTrail.setCityName(bAreas.get(0).getName());
            }
        }
        if (StringUtils.isNotBlank(cWaybillTrail.getCountyCode())) {
            BAreaExample example1 = new BAreaExample();
            example1.createCriteria().andCodeEqualTo(cWaybillTrail.getCountyCode());
            List<BArea> bAreas = this.getBAreaMapper().selectByExample(example1);
            if (CollectionUtils.isNotEmpty(bAreas)) {
                cWaybillTrail.setCountyName(bAreas.get(0).getName());
            }
        }
        String gps = this.getGDMapService().getLongitudeAndLatitudeByAddress(cWaybillTrail.getProvinceName() + cWaybillTrail.getCityName() + cWaybillTrail.getCountyName());
        String[] str = gps.split(",");
        cWaybillTrail.setLongitude(new BigDecimal(str[0]));
        cWaybillTrail.setLatitude(new BigDecimal(str[1]));
        LOGGER.info("GPS : {},{}", str[0], str[1]);
        // 增加在途信息
        this.getCWaybillTrailMapper().insertSelective(cWaybillTrail);
        // 查询运单明细
        CWaybillDetailExample cd = new CWaybillDetailExample();
        cd.createCriteria().andWaybillIdEqualTo(cWaybillTrail.getWaybillId());
        List<CWaybillDetail> cWaybillDetails = this.getCWaybillDetailMapper().selectByExample(cd);
        if (CollectionUtils.isNotEmpty(cWaybillDetails)) {
            for (CWaybillDetail cWaybillDetail : cWaybillDetails) {
                SServiceOrderTrail trail = new SServiceOrderTrail();
                String path = cWaybillTrail.getProvinceName() == cWaybillTrail.getCityName() ? "" : cWaybillTrail.getCityName();
                trail.setInfo(cWaybillTrail.getProvinceName() + path + cWaybillTrail.getCountyName() + cWaybillTrail.getAddr());
                trail.setServiceOrderId(cWaybillDetail.getServiceOrderId());
                trail.setStatus(0);
                trail.setType(SServiceOrderTrailTypeEnum.SERVICE_ORDER_ADDR.getValue());
                // 增加服务订单物流信息
                this.getSServiceOrderTrailService().add(trail);
            }
        }
        return cWaybillTrail.getId();
    }

    @Override
    public List<CWaybillTrail> selectByWaybillId(Long waybillId) {
        LOGGER.info("selectByWaybillId param : {}", waybillId);
        if (waybillId == null) {
            LOGGER.info("waybillid is not null");
            throw new BusinessException("运单ID不能为空");
        }
        CWaybillTrailExample example = new CWaybillTrailExample();
        example.setOrderByClause("id desc");
        example.createCriteria().andWaybillIdEqualTo(waybillId);
        List<CWaybillTrail> list = this.getCWaybillTrailMapper().selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {
            LOGGER.info("selectByExample result records : {}", list.size());
            return list;
        }
        return null;
    }

}
